/**
 * 聊天窗口操作,
 * yangfan 样式改变较大，重写 1.0.0 代码
 */
fangimjs.define("view/chatWindowView", [
    "jquery"
], function (require, exports, module) {
    "use strict";
    var $ = require("jquery"),
        base = fangimjs.data.base,
        vars = fangimjs.data.vars;

    function chatWindowView() {
        this.chatWAlert = '#chatW_l_alert'
        this.chatWMsg = '#chatW_l_msg'; //消息显示容器id
        this.chatLTitle = '#chatW_L_DX'; //当前联系人信息容器
        this.onlineClass = 'online'; //在线联系人样式类名
        this.avatar = 'http://js.soufunimg.com/common_m/m_public/images/fang.jpg';
        this.userAvatar = vars.config.avatar || base + 'images/user.png';
    };
    chatWindowView.prototype = {
        init: function () {
            this.$chatLTitle = $(this.chatLTitle);
            this.msgShow = $(this.chatWMsg);
            this.alertShow = $(this.chatWAlert);
        },
        /**
         * 更新显示消息，
         * 如果是数据说明是消息列表，需要刷新全部
         * 如果一条消息 添加到底部
         * @param data
         */
        updateMsg: function (data, history) {
            var that = this;
            var htmlArr = [];
            var msgS = that.msgShow;
            //TODO:显示离线回复消息

            if ($.isArray(data)) {
                //消息列表，需要刷新全部
                //msgS.empty();
                var len = data.length;
                if (history) {
                    htmlArr.push('<li>-----' + (len > 0 ? '本地消息记录如下' : '无本地消息记录') + '-----</li>');
                }
                for (var i = 0; i < len; i++) { //这种方式要比for in快
                    htmlArr.push(that.makeMsgStr(data[i]));
                }
                msgS.html(htmlArr.join(''));
            } else if (data.command === 'forbidden') {
                var lastME = this.msgShow.find('li.me').last();
                lastME.append('<div class="icon_send_error"><span>!</span></div>');
                msgS.append('<li class="replyforbidden"><span>您已被系统禁言</span></li>');
            } else {
                //一条消息 添加到底部
                msgS.append(that.makeMsgStr(data));
            }
            //将滚动条滚动到最下
            msgS.parent().animate({ scrollTop: msgS.height() }, 200);
        },
        /**
         * 拼接消息显示的html字符串
         * @param data
         * @returns {string}
         */
        makeMsgStr: function (data) {
            var that = this;
            var html = '' +
                '<li class="{{im_chat_class}}">' +
                '{{im_user_image}}' +
                '<div class="replybox">' +
                '<div class="replycontent">' +
                '<span class="arrow">&nbsp;</span>{{im_chat_content}}' +
                '</div>' +
                '</div>' +
                '</li>';
            html = html.replace(/{{im_chat_class}}/g, data.msgMine ? 'even me' : 'odd chatother');

            // 头像
            var $image = $('<div>' +
                '<a class="user" target="_blank">' +
                '<img src="' + that.userAvatar + '" width="46" height="46" />' +
                '</a>' +
                '</div>');
            if (!data.msgMine) {
                $image.find('img').attr('src', that.avatar);
            }
            html = html.replace(/{{im_user_image}}/g, $image.html());

            // 对话内容
            var content = that.getContentByCommand(data.command, data.purpose, data.content);
            html = html.replace(/{{im_chat_content}}/g, content);
            return html;
        },
        getContentByCommand: function (command, purpose, content) {
            var that = this,
                html = '',
                json = null,
                array = [];
            switch (command) {
                case 'img':
                    html = '<a href="' + content + '" target="_blank"><img src="' + content + '" width="100"/></a>';
                    break;
                case 'com_card':
                    json = JSON.parse(content);
                    html = ['<div style="width:272px;">',
                        '<div class="refy">' + that.textOverflow(json.title1, 18) + '</div>',
                        '<div class="refytr02">',
                            '<div class="sl"><a href="' + json.wapurl + '" target="_blank"><img src="' + json.img + '" width="80" height="60"></a></div>',
                            '<div class="sr">',
                                '<h2><a href="' + json.wapurl + '" target="_blank">' + that.textOverflow(json.title2, 8) + '</a></h2>',
                                '<p>' + json.desc1 + '   ' + json.desc2 + '</p>',
                                '<p><span class="red">' + json.tap1 + '</span></p>',
                                '<div class="zybq">' + json.fromtype + '</div>',
                        '</div></div></div>'
                    ].join('');
                    break;
                case 'namecard':
                    json = JSON.parse(content);
                    html = ['<div style="width:272px;">',
                        '<div class="refya"><span>' + that.textOverflow(json.rightuptip, 23) + '</span>个人名片</div>',
                        '<div class="refytr02">',
                            '<div class="sla"><a href="javascript:void(0);"><img src="' + json.photourl + '" width="80" height="60"></a></div>',
                            '<div class="sr w170">',
                                '<h2><a href="javascript:void(0);">' + json.nameline + '</a></h2>',
                                '<ul><li>' + that.textOverflow(json.description1, 28) + '</li>',
                                '<li>' + that.textOverflow(json.description2, 28) + '</li></ul>',
                        '</div></div></div>'
                    ].join('');
                    break;
                case 'red_packets_cash':
                case 'red_packets_cash_ret':
                    html = '[现金红包]';
                    break;
                case 'newhouses':
                    // 0:经纪人id;
                    // 1:城市;
                    // 2:客户端os;
                    // 3:图片;
                    // 4:楼盘名称;
                    // 5:优惠信息;
                    // 6:均价;
                    // 7:户型;
                    // 8:面积;
                    // 9:户型描述;
                    // 10:url;
                    array = content.split(';');
                    var title = {
                        'xfb_soufun_redbag': '房天下红包',
                        'xfb_house': '楼盘',
                        'xfb_huxing': '户型',
                    }[purpose];
                    html = '<a title="' + array[4] + '" href="' + array[10] + '" target="_blank">[' + title + '] ' + array[4] + ' ' + array[10] + '</a>';
                    break;
                case 'house':
                    // 0:房源id;
                    // 1:cs(二手房)cz(租房);
                    // 2:城市;
                    // 3:图片;
                    // 4:楼盘名称;
                    // 5:室;
                    // 6:厅;
                    // 7:卫;
                    // 8:面积;
                    // 9:价格;
                    // 10:经纪人id;
                    // 11:B端类型;
                    // 12:小区类型;
                    // 13:verifyCode;
                    // 14:url;;;
                    array = content.split(';');
                    html = '<a title="' + array[4] + '" href="' + array[14] + '" target="_blank">[房源] ' + array[4] + ' ' + array[14] + '</a>';
                    break;
                case 'voice':
                    html = '[语音]';
                    break;
                case 'video':
                    html = '[视频]';
                    break;
                case 'location':
                    html = '[位置]';
                    break;
                default:
                    if (purpose === 'anli') {
                        array = content.split(';');
                        html = '<a title="'+ array[0] +'" href="' + array[1] + '" target="_blank">[案例] ' + array[0] + ' ' + array[0] + '</a>';
                    } else {
                        html = that.replaceFace(content);
                    }
                    break;
            }
            return html;
        },
        textOverflow: function (pString, pLength) {
            var length = pLength || 10,
                string = pString;
            return string.length > length ? string.substr(0, length) + '...' : string;
        },
        // 把对应的表情字符转换成表情src
        replaceFace: function (pStr) {
            var emojis = fangimjs.data.vars.emojis;
            var str = pStr.replace(/\[([^\]]*)\]/g, function () {
                if (!emojis[arguments[1]]) {
                    return '[' + arguments[1] + ']';
                }
                return '<img src="' + base + 'images/emoji_s/' + emojis[arguments[1]] + '" width="24" border="0" />';
            });

            // 转义放到显示，发送时不转义
            if (!str) {
                str = $.trim(str);
                str = str.replace(/\</g, '&lt;');
                str = str.replace(/\>/g, '&gt;');
                str = str.replace(/\"/g, '&quot;');
                str = str.replace(/\s+/g, '&nbsp;');
                str = str.replace(/\n/g, '<br/>');
            }

            return str;
        },
        /**
         * 更新当前联系人信息
         * @param {Object} data
         */
        updateInfo: function (data) {
            var that = this;
            // 新需求：shop 不再是店铺url地址，改为楼盘名称
            if (data.hasOwnProperty('loupan') && data.loupan) {
                var loupan = data.loupan.length > 20 ? data.loupan.substr(0, 20) + '...' : data.loupan;
                that.$chatLTitle.find('.im_name').html(loupan + ': ' + data.showname + '为您服务');
            } else {
                that.$chatLTitle.find('.im_name').html(data.showname + '为您服务');
            }
            // 移除需求，当存在shop时，可以点击跳转到经纪人店铺否则无操作
            // 存在电话号码时显示电话号码
            if (data.hasOwnProperty('tel') && data.tel) {
                that.$chatLTitle.find('.im_tel').html(data.tel).show();
            } else {
                that.$chatLTitle.find('.im_tel').hide();
            }
            // 存在用户头像时设置用户头像否则显示默认头像
            if (data.hasOwnProperty('avatar') && data.avatar) {
                that.$chatLTitle.find('.im_head_img').html('<img src="' + data.avatar + '" alt="' + data.showname + '">');
                that.avatar = data.avatar;
            } else {
                that.$chatLTitle.find('.im_head_img').html('<img src="' + that.avatar + '" alt="' + data.showname + '">');
            }
            var $status = that.$chatLTitle.find('.im_status');
            if (data.state != 1) {
                $status.removeClass(that.onlineClass);
            } else {
                $status.addClass(that.onlineClass);
            }
        },
        /**
         * 显示提示信息
         * @param {Object} d 需要提示的内容
         */
        showAlert: function (d) {
            var $li = $('<li>*****' + d + '*****</li>');
            this.msgShow.append($li);
            $li.fadeOut(1000);
            this.msgShow.parent().animate({ scrollTop: this.msgShow.height() }, 200);
        },
        /**
         * 显示消息（断线或者重连之类得服务器信息）
         **/
        showMsgString: function (d) {
            var $li = $('<li>*****' + d + '*****</li>');
            this.msgShow.append($li);
            this.msgShow.parent().animate({ scrollTop: this.msgShow.height() }, 200);
        }
    };
    module.exports = new chatWindowView;
});
